import axios from 'axios'
import store from '../../store/index'
import addMenu from './addMenu'

// import router from '../../router/index'
axios.defaults.timeout = 1000000
axios.defaults.baseURL = ''
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

axios.interceptors.request.use(config => {
  if (store.state.user.token) {
    config.headers['x-access-token'] = `${store.state.user.token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(config => {
  if (config.config.url === '/index/login' || config.config.url === '/index/pullUser') {
    if (config.data.code === 0) {
      addMenu(config.data.data.groupId.menuData)
      store.dispatch('set_user', config.data)
    } else if (config.data.code === 401) {

    }
  }
  return config
}, error => {
  if (error.response) {
    if (error.response.status === 401) {
      // 401 清除token信息并跳转到登录页面
      // router.replace(
      //   {
      //     path: 'login',
      //     query: {redirect: router.currentRoute.fullPath}
      //   }
      // )
      // store.commit(allType.user.SET_USER, {})
      // goodStorage.remove('user')
    }
  }
  return Promise.reject(error)
})

export default axios
